import os
from datetime import datetime, date

import akshare as ak
import pandas as pd
# from config.strategy_config import stocks_manage_file_path
from retry import retry
from service import stock_pool

from python_quant.common import constant
from python_quant.common.code import code_to_shse_szse_symbol
from python_quant.common.date import date_to_str
from python_quant.quant_api.juejin.order import is_position_trading
from python_quant.stock.mootdx import init_tdx, get_up_and_down_max_amount_price
from python_quant.stock.side.amount_side import amount_side
from python_quant.stock.side.fundamentals_side import finance_side
from python_quant.stock.side.hot_pop_side import hot_pop_side
from python_quant.stock.side.tech_side import tech_side
from python_quant.stock.side.theme_side import theme_side

# sys.path.append("..")
# sys.path.insert(0,"..")


"""
多因子选股策略
"""


class NewStockFilterStrategy:

    @retry(tries=5, delay=1, backoff=1, jitter=(5, 7))
    def do_test(self, context):
        print(context.user_data)
        raise Exception("My Exception")

    @retry(tries=5, delay=1, backoff=1, jitter=(5, 7))
    def do_select(self):
        print('newStockFilterStrategy do_select process %s.' % os.getpid())
        # 题材面
        theme_stocks = theme_side.theme_stocks()
        # 资金面
        amount_stocks = amount_side.amount_stocks()

        remix_code_df = pd.merge(amount_stocks, theme_stocks, how='inner', on=['代码']).drop_duplicates()
        remix_code_list0 = remix_code_df['代码'].values

        # 基本面 - 财务
        remix_code_list1 = finance_side.finance_stocks(remix_code_list0)

        # 技术面 - 估价
        remix_code_list2 = tech_side.tech_stocks(remix_code_list1)

        # 基本面 - 估值
        # remix_code_list3 = valuation_side.valuation_stocks(remix_code_list2)

        # 人气面 - 人气上升
        remix_code_list4 = hot_pop_side.hot_pop_stocks(remix_code_list2)

        # 写入stocks_manage sql
        stock_pool.add_to_stocks_pool(remix_code_list4)
        return remix_code_list4

    @retry(tries=5, delay=1, backoff=1, jitter=(5, 7))
    def do_update(self):
        print('newStockFilterStrategy do_update process %s.' % os.getpid())
        stocks_pool = stock_pool.select_all_valid_stock_pool()
        if len(stocks_pool) == 0:
            return
        # 初始化tdx
        client = init_tdx(None)
        # 更新支撑压力位
        for stock in stocks_pool:
            today = date.today()
            date_today = date_to_str(today, constant.DATE_FORMAT_PARTTERN_Y_M_D)
            up_down_price_df = get_up_and_down_max_amount_price(client, stock['symbol'], date_today,
                                                                None)
            stock_pool.update_stock_pool(
                round(float(up_down_price_df['up_price']), 2),
                round(float(up_down_price_df['up_amount']), 2),
                round(float(up_down_price_df['up_rate']), 2),
                round(float(up_down_price_df['down_price']), 2),
                round(float(up_down_price_df['down_amount']), 2),
                round(float(up_down_price_df['down_rate']), 2),
                round(float(up_down_price_df['close']), 2),
                stock['id']
            )
        client.close()


@retry(tries=10, delay=10, backoff=1)
def code_can_trade_and_write_new_excel(context, remix_code_list):
    """
    if os.path.exists(stocks_manage_file_path):
        stock_manage_df = pd.read_excel(stocks_manage_file_path,sheet_name="选股建仓")
    else:
        excel_writer = pd.ExcelWriter(stocks_manage_file_path)
        form_header = ['股票代码', '筛选日期', '是否正在持仓', '建仓日期', '建仓价格', '止盈百分比', '止盈价格']
        stock_manage_df = pd.DataFrame(columns=form_header)
        stock_manage_df.to_excel(excel_writer, sheet_name="选股建仓", index=False)
        excel_writer.save()
    """

    stock_manage_df = pd.DataFrame(
        columns=['股票代码', '入选价格', '入选日期', '建仓价格', '建仓日期', '建仓金额', '建仓股数'])
    stock_zh_a_spot_em_df = ak.stock_zh_a_spot_em()
    code_to_trade = list()
    for code in remix_code_list:
        full_code = code_to_shse_szse_symbol(code)
        is_true = is_position_trading(context, full_code)
        if not is_true:
            code_df = stock_zh_a_spot_em_df[(stock_zh_a_spot_em_df['代码'] == code)]
            stock_manage_df = stock_manage_df.append(
                {'股票代码': full_code, '入选价格': float(code_df['最新价']), '入选日期': datetime.now()},
                ignore_index=True)
            code_to_trade.append(full_code)
    # writer = pd.ExcelWriter(stocks_manage_file_path)

    # stock_manage_df.to_excel(excel_writer=writer, index=False)
    # writer.save()
    print("Success")
    return code_to_trade
